package com.castudio.Controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.castudio.COS.qiniu.service.QiNiuService;
import com.castudio.Entity.Image;
import com.castudio.Filter.R;
import com.castudio.Filter.Result;
import com.castudio.Service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 小陈同学
 * @since 2023-03-25
 */
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ImageService imageService;

    @Autowired
    private QiNiuService qiNiuService;

    @GetMapping("/all")
    public List<Image> listAll() {
        return imageService.list();
    }

    @PostMapping("/add")
    public Result add(@RequestBody Image image) {
        return imageService.save(image) ? Result.success() : Result.failure();
    }

    @PostMapping("/delete")
    public Result delete(Integer id) {
        return imageService.removeById(id) ? Result.success() : Result.failure();
    }

    @PostMapping("/Obscure")
    public Result Obscure(@RequestBody Image image) {
        LambdaQueryWrapper<Image> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(image.getName())) {
            queryWrapper.like(Image::getName, image.getName());
        }
        return Result.success(imageService.list(queryWrapper));
    }

    /*    @PostMapping("/page/")
        public RespPageEntity getAllImage(@RequestParam(defaultValue = "1")Integer page,
                                          @RequestParam(defaultValue = "20")Integer size,
                                          @RequestParam(defaultValue = "")String name){
            return imageService.getAllImage(page,size,name);
        }*/
    @GetMapping("/{currentPage}/{PageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer PageSize, Image image) {
        IPage<Image> page = imageService.getPage(currentPage, PageSize, image);
        //如果当前页码之大于总页码值，重新执行查询操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages())//如果当前页码之大于总页码值
            page = imageService.getPage((int) page.getPages(), PageSize);//使用最大页码作为当前页码值
        return new R(true, page);
    }

    @PostMapping("/uploadFile")
    public JSONObject uploadFile(HttpServletRequest req) {
        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile file = mreq.getFile("file");
            if (file.getSize() == 1) {
                String path = "/CAStudio";
                // String fileUrl = COSConfig.uploadFile(file, path, req.getServletContext());
                InputStream inputStream = file.getInputStream();
                String fileUrl = qiNiuService.uploadFile(inputStream, path);

                /*获得前端数据*/
                String name = req.getParameter("name");

                data.put("code", 200);
                data.put("msg", "上传成功");
                data.put("fileUrl", fileUrl);
                System.out.println(fileUrl);
                System.out.println(name);

                imageService.save(fileUrl, name);

                return data;
            } else {
                data.put("code", 400);
                data.put("msg", "请上传文件");
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code", 500);
            data.put("msg", "网络开小差了");
            return data;
        }
    }
}
